(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.popup.adSortFieldController', adSortFieldController);
	adSortFieldController.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService','reportService' ];
	function adSortFieldController($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService, reportService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("adSortFieldLookup");
		ctrl.dialogsModule = dialogsModule;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		
		ctrl.ok = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['ok'] || dialogsModule.btnCallback['ok'](ctrl.reportAdSortField.list) !== false) {
				$uibModalInstance.close();
			}
		};
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
		ctrl.init = function() {
			ctrl.reportAdSortField = {};
			if (ctrl.dialogsModule.params.filterAdrptCode) {
				ctrl.reportAdSortField.adrptCode = ctrl.dialogsModule.params.filterAdrptCode;// get params from parent page
			}
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.fieldCfg.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.reportAdSortField.list';
			authService.search(ctrl.reportAdSortField).then(function(response) {
				ctrl.reportAdSortField.list = response.data || [];
				if (ctrl.dialogsModule.params.filterSortBy) {
					initSortFieldList(ctrl.dialogsModule.params.filterSortBy);// get params from parent page
				}
			});
			reportService.getReportSortSequenceOptions(ctrl.reportAdSortField).then(function(response) {
				ctrl.sortSequenceOptions = response;
			});
		};
		function trimStr(str) {
			return str.replace(/(^\s*)|(\s*$)/g, "");
		}
		function initSortFieldList(fieldString){
			var fieldArr = fieldString.split(",");
			for(var i = 0; i < fieldArr.length; i++){
				var fieldName = "";
				var sortValue = "D";
				if(fieldArr[i].indexOf("DESC") == -1){
					fieldName = trimStr(fieldArr[i]);
					sortValue = "A";
				} else {
					fieldName = trimStr(fieldArr[i].substring(0, fieldArr[i].indexOf("DESC")));
				}
				angular.forEach(ctrl.reportAdSortField.list, function(selectedField, key) {
					if (fieldName == selectedField.fieldName) {
						selectedField.sortDirection = sortValue;
						selectedField.sortSequence = i + 1;
					}
				});
			}
		}


		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}

		
	}
})(angular);
